from django.conf import settings
import sys
import os

def setup_env(settings_mod):
	"""Copied and modified from django.core.managment.execute_manager"""
	project_directory = os.path.dirname(settings_mod.__file__)
	sys.path.append(os.path.join(project_directory))

setup_env(__import__(settings.SETTINGS_MODULE,[],[],[]))


def run_compiler():
	"""Runs compiler once"""
	from compiler import compile
	from pacs.models import Submission
	for s in Submission.objects.filter(compiled__isnull=True):
		compile(s)

def run_tester():
	"""Run tester once"""
	from tester import run_test
	from pacs.models import TestResults
	for tr in TestResults.objects.filter(status=10,test__checkTime__isnull=False).order_by("pacs_testresults__test.checkTime"):
		run_test(tr)

def run_points_updater():
	"""Runs points updater once"""
	from points_updater import update_goals,update_goals_results
	update_goals()
	update_goals_results()

cmdFuncs = {'points_updater':run_points_updater, 'compiler':run_compiler, 'tester':run_tester}

class BadUsage(Exception):
	"""Bad usage of program"""

def run(what):
	try:
		funcs = map(cmdFuncs.__getitem__,what)
	except KeyError:
		raise BadUsage
	from time import sleep
	if settings.DEBUG:
		from django import db
	while True:
		for func in funcs:
			func()
		if settings.DEBUG:
			db.reset_queries() #when this is not set, program memory use will be growing
		sleep(0.1)
run.usage = "run [what1 what2], where what in "+', '.join(cmdFuncs.keys())

def run_all(args):
	run(["compiler","tester","points_updater"])
run_all.usage = "run_all"

def rejudge(what):
	from pacs.models import Task
	for slug in what:
		try:
			task = Task.objects.get(slug=slug)
		except Task.DoesNotExist:
			raise BadUsage,"No such task: %s"%slug
		for s in task.submission_set.all():
			s.compiled = None
			s.save()
rejudge.usage = "rejudge task_slug1 task_slug2"

def print_usage(what=None):
	if what == None:
		print "Usage:\tmanage.py command [options]"
		print "Where commands are(with options needed):"
		for c in commands.values():
			print '\t',c.usage
	else:
		print "Usage:\tadmin.py",commands[what].usage

commands =\
		{
			'run':run,
			'run_all':run_all,
			'rejudge':rejudge,
		}

if __name__ == "__main__":
	if len(sys.argv) < 2:
		print_usage()
	else:
		try:
			commands[sys.argv[1]](sys.argv[2:])
		except KeyError:
			print_usage()
		except BadUsage,e:
			print e
			print_usage(sys.argv[1])
